<?php

namespace App\Http\Controllers\Admin;

use App\Models\NewAdmin;
use App\Models\ShopTrans;
use App\Models\ShopUser;
use App\Models\ShopWithdrawal;
use App\Services\AlipayService;
use App\Services\CommonService;
use App\Services\ExportService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class WithdrawalController extends BaseController
{
    /**
     * 提现审核列表
     * @param Request $request
     * @return false|string
     */
    public function withdrawalExamineList(Request $request){
        $payeeName = $request->input('payeeName','');
        $payeeAccount = $request->input('payeeAccount','');
        $shopName = $request->input('shopName','');
        $applyTime = $request->input('applyTime','');
        $arrivalTime = $request->input('arrivalTime','');
        $status = $request->input('status','');
        $page = $request->input('page',1);
        $pageSize = $request->input('pageSize',10);
        $where = [];
        if($payeeName){
            $where[] = ['w.payee_name','like','%'.$payeeName.'%'];
        }
        if($payeeAccount){
            $where[] = ['w.payee_account','like','%'.$payeeAccount.'%'];
        }
        if($shopName){
            $where[] = ['s.shopname','like','%'.$shopName.'%'];
        }
        if($status){
            $where[] = ['w.status',$status];
        }
        if($applyTime){
            $applyTime = explode('~', $applyTime);
            $where[] = ['w.apply_time','>=',$applyTime[0]];
            $where[] = ['w.apply_time','<',$applyTime[1]];
        }
        if($arrivalTime){
            $arrivalTime = explode('~', $arrivalTime);
            $where[] = ['w.arrival_time','>=',$arrivalTime[0]];
            $where[] = ['w.arrival_time','<',$arrivalTime[1]];
        }
        $list = ShopWithdrawal::from('sp_shop_withdrawal as w')
            ->leftjoin('sp_shop_user_2 as s','s.member_id','w.member_id')
            ->select(
                's.shopname'
                ,'w.id','w.member_id','w.withdrawal_amount','w.payee_name','w.payee_account','w.alipay_trade_no','w.out_biz_no','w.out_biz_no'
                ,'w.pay_type','w.status','w.refuse_reason','w.apply_time','w.check_time','w.admin_id','w.arrival_time'
            )
            ->where($where)
            ->orderBy('w.id','desc')
            ->paginate($pageSize);
        $list = obToArray($list);
        if(isset($list['data']) && $list['data']){
            foreach ($list['data'] as $k=>$item){
                $list['data'][$k]['admin_name'] = NewAdmin::where(['id'=>$item['admin_id']])->value('mobile');
            }
        }
        //对应状态统计
        $listCount = ShopWithdrawal::from('sp_shop_withdrawal as w')
            ->leftjoin('sp_shop_user_2 as s','s.member_id','w.member_id')
            ->select('w.status',DB::raw('count(*) as count'))
            ->where($where)
            ->groupBy('w.status')
            ->get();
        $listCount = obToArray($listCount);
        if($listCount){
            $totalCount = 0;
            foreach ($listCount as $k=>$v){
                $totalCount += $v['count'];
            }
            $listCount[] = ['status'=>'all','count'=>$totalCount];
        }
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',['count'=>$listCount,'list'=>$list]);
    }

    /**
     * 提现审核列表导出
     * @param Request $request
     * @return false|string
     */
    public function withdrawalExamineListExport(Request $request){
        $data = ExportService::withdrawalExamineListExport($request);
        if(!$data){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'无数据');
        }
        $params = $request->input();
        ExportService::exportFile($params,$data,ExportService::FILE_WITHDRAWAL_CHECK_LIST);
    }

    /**
     * 提现记录
     * @param Request $request
     * @return false|string
     */
    public function withdrawalList(Request $request){
        $adminMobile = $request->input('adminMobile','');
        $arrivalTime = $request->input('arrivalTime','');
        $status = $request->input('status','');
        $shopName = $request->input('shopName','');
        $page = $request->input('page',1);
        $pageSize = $request->input('pageSize',10);
        $where = [];
        if($adminMobile){
            $adminId = NewAdmin::where(['mobile','like','%'.$adminMobile.'%'])->value('id');
            $where[] = ['w.apply_admin_id',$adminId];
        }
        if($status){
            $where[] = ['w.status',$status];
        }
        if($shopName){
            $where[] = ['s.shopname','like','%'.$shopName.'%'];
        }
        if($arrivalTime){
            $arrivalTime = explode('~', $arrivalTime);
            $where[] = ['w.apply_time','>=',$arrivalTime[0]];
            $where[] = ['w.apply_time','<',$arrivalTime[1]];
        }
        $list = ShopWithdrawal::from('sp_shop_withdrawal as w')
            ->leftjoin('sp_other_admin as a','a.id','w.apply_admin_id')
            ->leftjoin('sp_shop_user_2 as s','s.member_id','w.member_id')
            ->select(
                's.shopname','a.mobile','a.username'
                ,'w.id','w.member_id','w.withdrawal_amount','w.payee_name','w.payee_account','w.alipay_trade_no','w.out_biz_no'
                ,'w.pay_type','w.status','w.refuse_reason','w.apply_time','w.check_time','w.admin_id','w.arrival_time'
            )
            ->where($where)
            ->orderBy('w.id','desc')
            ->paginate($pageSize);
        $list = obToArray($list);
        if(isset($list['data']) && $list['data']){
            foreach ($list['data'] as $k=>$item){
                $list['data'][$k]['admin_name'] = NewAdmin::where(['id'=>$item['admin_id']])->value('mobile');
            }
        }
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$list);
    }

    /**
     * 获取提现审核验证码 手机号
     * @return false|string
     */
    public function getExamineMobile(){
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',['mobile'=>ShopWithdrawal::WITHDRAWAL_EXAMINE_MOBILE_CODE]);
    }

    /**
     * 提现审核通过
     * @param Request $request
     * @return false|string
     */
    public function withdrawalPass(Request $request){
        try{
            $id = $request->input('id','');
            $mobile = $request->input('mobile','');
            $code = $request->input('code','');
            if(!$id){
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'参数错误');
            }
//            if($mobile != ShopWithdrawal::WITHDRAWAL_EXAMINE_MOBILE_CODE){
//                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'审核手机号不存在');
//            }
//            $checkCode = SmsService::checkCode($mobile,$code);
//            if(!$checkCode){
//                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'验证码错误');
//            }
            $log = ShopWithdrawal::where(['id'=>$id,'status'=>ShopWithdrawal::WITHDRAWAL_STATUS_REVIEWED])->select('id','withdrawal_amount','member_id','payee_name','payee_account')->first();
            $log = obToArray($log);
            if(!$log){
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'未找到待审核的提现记录');
            }
            ShopWithdrawal::where(['id'=>$id])->update(['status'=>ShopWithdrawal::WITHDRAWAL_STATUS_TRANS_FAIL]);
            $shopname = ShopUser::where(['member_id' => $log['member_id']])->value('shopname');
            $params = [
                'amount' => $log['withdrawal_amount'],
                'payeeRealName' => $log['payee_name'],
                'payeeAccount' => $log['payee_account'],
                'remark' => $shopname . '提现',
            ];
            $res = AlipayService::alipayCertTransferAccounts($params);
            if($res['status'] && isset($res['data']['pay_fund_order_id'])){
                DB::beginTransaction();
                ShopUser::where(['member_id'=>$log['member_id']])->decrement('frozen_amount',$log['withdrawal_amount']);
                $data = [
                    'check_time' => dateFormat(time()),
                    'arrival_time' => $res['data']['trans_date'],
                    'status' => ShopWithdrawal::WITHDRAWAL_STATUS_TRANS_SUCCESS,
                    'admin_id'=>$this->users['id'],
                    'out_biz_no' => $res['data']['out_biz_no'],
                    'alipay_trade_no' => $res['data']['pay_fund_order_id'],
                    'result' => json_encode($res['data']),
                ];
                ShopWithdrawal::where(['id'=>$id])->update($data);
                DB::commit();
                return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'操作成功');
            }else{
                $data = [
                        'result' => json_encode($res['data']),
                        'status' => ShopWithdrawal::WITHDRAWAL_STATUS_REVIEWED,
                ];
                ShopWithdrawal::where(['id'=>$id])->update($data);
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,isset($res['data']['sub_msg']) ? $res['data']['sub_msg'] :'操作失败');
            }
        }catch (\Exception $exception){
            DB::rollBack();
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'操作失败'.$exception->getMessage().$exception->getFile().$exception->getLine());
        }
    }

    /**
     * 提现审核拒绝
     * @param Request $request
     * @return false|string
     */
    public function withdrawalRefuse(Request $request){
        try {
            $id = $request->input('id','');
            $remark = $request->input('remark','');
            if(!$id || !$remark){
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'参数错误');
            }
            $log = ShopWithdrawal::where(['id'=>$id,'status'=>ShopWithdrawal::WITHDRAWAL_STATUS_REVIEWED])->select('id','withdrawal_amount','member_id','payee_name','payee_account')->first();
            $log = obToArray($log);
            if(!$log){
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'未找到待审核的提现记录');
            }
            ShopWithdrawal::where(['id'=>$id])->update(['status'=>ShopWithdrawal::WITHDRAWAL_STATUS_REFUSE]);
            DB::beginTransaction();
            $shop_balance = ShopUser::where(['member_id'=>$log['member_id']])->value('shop_balance');
            $shop_trans_data = array(
                'member_id' => $log['member_id'],
                'amount' => $log['withdrawal_amount'],
                'before_balance' => $shop_balance,
                'after_balance' => $shop_balance + $log['withdrawal_amount'],
                'trans_type' => ShopTrans::ORDER_TRANS_TYPE_WITHDRAWAL,
                'remarks' => '商户提现审核拒绝',
                'create_time' => dateFormat(time()),
            );
            ShopTrans::addData($shop_trans_data);
            $data = [
                'check_time' => dateFormat(time()),
                'refuse_reason' => $remark,
                'status' => ShopWithdrawal::WITHDRAWAL_STATUS_REFUSE,
                'admin_id'=>$this->users['id'],
            ];
            ShopWithdrawal::where(['id'=>$id])->update($data);
            ShopUser::where(['member_id'=>$log['member_id']])->increment('shop_balance',$log['withdrawal_amount']);
            ShopUser::where(['member_id'=>$log['member_id']])->decrement('frozen_amount',$log['withdrawal_amount']);
            DB::commit();
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'操作成功');
        }catch (\Exception $exception){
            DB::rollBack();
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'操作失败');
        }
    }

    /**
     * 提现记录
     * @param Request $request
     * @return false|string
     */
    public function withdrawalListExport(Request $request){
        $adminMobile = $request->input('adminMobile','');
        $arrivalTime = $request->input('arrivalTime','');
        $status = $request->input('status','');
        $shopName = $request->input('shopName','');
        $where = [];
        if($adminMobile){
            $adminId = NewAdmin::where(['mobile','like','%'.$adminMobile.'%'])->value('id');
            $where[] = ['w.apply_admin_id',$adminId];
        }
        if($status){
            $where[] = ['w.status',$status];
        }
        if($shopName){
            $where[] = ['s.shopname','like','%'.$shopName.'%'];
        }
        if($arrivalTime){
            $arrivalTime = explode('~', $arrivalTime);
            $where[] = ['w.apply_time','>=',$arrivalTime[0]];
            $where[] = ['w.apply_time','<',$arrivalTime[1]];
        }
        $list = ShopWithdrawal::from('sp_shop_withdrawal as w')
            ->leftjoin('sp_other_admin as a','a.id','w.apply_admin_id')
            ->leftjoin('sp_shop_user_2 as s','s.member_id','w.member_id')
            ->select(
                's.shopname','a.mobile','a.username'
                ,'w.id','w.member_id','w.withdrawal_amount','w.payee_name','w.payee_account','w.alipay_trade_no','w.out_biz_no'
                ,'w.pay_type','w.status','w.refuse_reason','w.apply_time','w.check_time','w.admin_id','w.arrival_time'
            )
            ->where($where)
            ->orderBy('w.id','desc')
            ->get();
        $list = obToArray($list);
        if(!$list){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'无数据');
        }
        $data = [];
        foreach ($list as $k=>$item){
            $data[] = [
                'id'=>$item['id'],
                'shopname'=>$item['shopname'],
                'shop_admin'=>$item['mobile'].$item['username'],
                'withdrawal_amount'=>$item['withdrawal_amount'],
                'pay_type'=>'支付宝',
                'payee_account'=>$item['payee_account'].$item['payee_name'],
                'alipay_trade_no'=>' '.$item['alipay_trade_no'],
                'apply_time'=>$item['apply_time'],
                'check_time'=>$item['check_time'],
                'arrival_time'=>$item['arrival_time'],
                'status'=>ShopWithdrawal::WITHDRAWAL_STATUS_LIST[$item['status']],
                'refuse_reason'=>$item['refuse_reason'],
                'admin'=>' '.NewAdmin::where(['id'=>$item['admin_id']])->value('mobile')
            ];
        }
        $params = $request->input();
        if(isset($params['status']) && $params['status']){
            $params['status'] = ShopWithdrawal::WITHDRAWAL_STATUS_LIST[$params['status']];
        }
        ExportService::exportFile($params,$data,ExportService::FILE_WITHDRAWAL_LOG_LIST);
    }

}
